<?php
//=======================================
//###################################
// Created by Andrew "Lord d'Eath" Gillard - http://www.lorddeath.net/
//
// Created for Craig Brass - http://www.subsonicsolutions.com/
//###################################
//=======================================


if (!defined("INSWIFT")) {
	trigger_error("Unable to process $PHP_SELF", E_USER_ERROR);
}

/**
* Initialization function. You can connect to your database etc over here.
*/
function loginShareInit()
{
	global $loginshare;

	$loginshare->moduleloaded = true;
}

/**
* Authorize a user based on email and password
*/
function loginShareAuthorize($username, $password)
{
	global $dbCore, $_SWIFT, $loginshare, $settings;

	$_loginshare = $settings->getSection("loginshare");

	$request = '<?xml version="1.0" encoding="UTF-8"?><soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"><soapenv:Body>' . '<ns1:getAccounts soapenv:encodingStyle="http://schemas.xmlsoap.org/soap/encoding/" xmlns:ns1="AdminServices"><at href="#id0"/></ns1:getAccounts>' . '<multiRef id="id0" soapenc:root="0" soapenv:encodingStyle="http://schemas.xmlsoap.org/soap/encoding/" xsi:type="ns2:AuthToken" xmlns:soapenc="http://schemas.xmlsoap.org/soap/encoding/" xmlns:ns2="urn:AdminServices"><accountId xsi:type="xsd:int">' . '0' . '</accountId><login xsi:type="xsd:string">' . htmlspecialchars($username) . '</login><password xsi:type="xsd:string">' . htmlspecialchars($password) . '</password><role xsi:type="ns2:Role" xsi:nil="true"/></multiRef></soapenv:Body></soapenv:Envelope>';

	$header = '';
	$header .= 'POST '.$_loginshare["hspurl"].' HTTP/1.0' . "\n";
	$header .= 'Content-Type: text/xml; charset="utf-8"' . "\n";
	$header .= 'Accept: application/soap+xml' . "\n";
	$header .= 'User-Agent: Kayako '.SWIFTPRODUCT.'v'.SWIFTVERSION . "\n";
	$header .= 'Cache-Control: no-cache' . "\n";
	$header .= 'Pragma: no-cache' . "\n";
	$header .= 'SOAPAction: ""' . "\n";
	$header .= 'Content-Length: ' . ( string ) strlen($request) . "\n\n";

	$_soapresult = sendSOAPRequest($_loginshare["hsphostserver"], $_loginshare["hspport"], $header, $request);

	$ids = array();
	$_authresult = false;
	$_remoteuserid = 0;
	if(!preg_match("/<item>([0-9]+)<\/item>/im", $_soapresult, $ids))
	{
		return false;
	} else {
		$_authresult = true;
		$_remoteuserid = $ids[1];
	}

	if ($_authresult == true)
	{
		$regpassword = substr(buildHash(),0,8);

		// We have a match, Seems like a valid user.. now see if he is registered..
		$userid = getLoginShareUser(LOGINAPI_HSPHERE, $_remoteuserid);
		if (!$userid)
		{
			// Not registered, Register him
			$userid = insertUser(true, "test@test.com", $regpassword, $_SWIFT["tgroup"]["regusergroupid"], LOGINAPI_HSPHERE, $_remoteuserid, $username, $_SWIFT["tgroup"]["languageid"], 0, false, 1, true);
		}

		if (!$userid)
		{
			return false;
		}

		$_swiftuser = $loginshare->loadSWIFTUser($userid);
		if (!$_swiftuser)
		{
			return false;
		}

		$_SWIFT["user"] = $_swiftuser;

		return $_swiftuser["userid"];
	}

	return false;
}

/**
* Send the Soap Request
*/
function sendSOAPRequest($hostname, $port, $header, $request)
{
	global $_SWIFT;

	$connect = fsockopen($hostname, $port, $errno, $errstr, 10);

	if (!$connect)
	{
		return $_SWIFT["language"]["hspconnectfail"];
	} else {
		fputs($connect, $header. $request);
		$response = '';
		$headerdone = false;

		stream_set_timeout($connect, 20);
		$status = socket_get_status($connect);
		while (!feof($connect) && !$status['timed_out'])
		{
			$data = fgets($connect, 1024);
			if (strcmp($data, "\r\n") == 0) 
			{
				$headerdone = true;
			} else if ($headerdone != false) {
				$response .= $data;
			}

			$status = socket_get_status($connect);
		}
	}

	@fclose($connect);

	return $response;
}

/**
* Return the Unique User ID of the current user
*/
function loginShareUserID()
{
	global $_SWIFT;

	if (empty($_SWIFT["user"]["userid"]))
	{
		return false;
	} else {
		return $_SWIFT["user"]["userid"];
	}
}

/**
* Logout the current user
*/
function loginShareLogout()
{
	global $session, $_SWIFT;

	$session->updateSession($_SWIFT["session"]["sessionid"], 0);

	return true;
}

/**
* Load the user credentials into current workspace. The following variables should be declared for proper working:
* userid - User id that is set in the "users" table
* fullname
* email - Array
* password (MD5 Hashed)
* usergroupid - If this is not set, then it will use the default registered user group for this template group
*/
function loginShareLoadUser()
{
	global $dbCore, $_SWIFT, $loginshare;

	if (empty($_SWIFT["session"]["typeid"]))
	{
		$_SWIFT["user"]["loggedin"] = false;
		return false;
	}

	$_user = $loginshare->loadSWIFTUser($_SWIFT["session"]["typeid"]);
	if (!$_user)
	{
		$_SWIFT["user"]["loggedin"] = false;

		return false;
	}

	$_SWIFT["user"] = $_user;

	return true;
}

/**
* Renders the Login Share Form
*/
function renderLoginShareForm()
{
	global $_SWIFT;

	$forms = array();

	$forms[0]["title"] = $_SWIFT["language"]["hsphostserver"];
	$forms[0]["name"] = "hsphostserver";
	$forms[1]["title"] = $_SWIFT["language"]["hspport"];
	$forms[1]["name"] = "hspport";
	$forms[2]["title"] = $_SWIFT["language"]["hspurl"];
	$forms[2]["name"] = "hspurl";

	return $forms;

}
?>